package com.carefree.system.modules.security.entity;


import com.alibaba.fastjson2.annotation.JSONField;
import com.carefree.system.modules.admin.entity.UserEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName:CustomUser
 * @Description: 步骤1:自定义 用户对象UserDetails
 * @Author Tengbin tengbin234@163.com
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomUserDetails implements UserDetails {

    /**
     * 数据库用户
     */
    private UserEntity userEntity;

    /**
     * 用户所拥有的权限列表
     */
    private List<String> permissionList;


    /**
     * security权限列表
     */
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    public CustomUserDetails(UserEntity userEntity, List<String> permissionList) {
        this.userEntity = userEntity;
        this.permissionList = permissionList;
    }

    /**
     * 获取当前用户密码
     *
     * @return
     */
    @Override
    public String getPassword() {
        return userEntity.getPassword();
    }

    /**
     * 获取当前用户名
     *
     * @return
     */
    @Override
    public String getUsername() {
        return userEntity.getUsername();
    }

    /**
     * 当前用户所拥有的权限列表
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        //permissionList.forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission.trim())));
        authorities = permissionList.stream().map(pers -> new SimpleGrantedAuthority(pers.trim())).collect(Collectors.toList());
        return authorities;
    }

    /**
     * 账户是否不过期
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否禁用
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 认证是否过期
     *
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return userEntity.getStatus().equals(1);
    }
}
